package com.zh.webcommon.common.auditor.mp;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zh.webcommon.common.auth.LoginUserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * mybatis-plus自动填充实体字段
 * 若要生效，需要注入到spring容器中
 * 或者开启 {@link com.zh.webcommon.EnableMybatisAudit}
 */
@Slf4j
@Component
public class MyBatisAuditorHandler implements MetaObjectHandler {
    public MyBatisAuditorHandler() {
        log.info("[MyBatisAuditorHandler] constructor ...");
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        log.trace("start insert fill ....");
        var user = LoginUserHolder.currentUserId();

        // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());

        if (metaObject.hasSetter("createBy")) {
            this.strictInsertFill(metaObject, "createBy", String.class, user);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.trace("start update fill ....");
        var user = LoginUserHolder.currentUserId();

        // 起始版本 3.3.0(推荐)
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        if (metaObject.hasSetter("updateBy")) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, user);
        }
    }

}
